package com.example.pei.ithinklearnt.view.fragments;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.adapter.NineGridTestAdapter;
import com.example.pei.ithinklearnt.bean.AlumniCircle;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.listener.QueryUserListener;
import com.example.pei.ithinklearnt.model.UserModel;
import com.example.pei.ithinklearnt.present.HomePresent;
import com.example.pei.ithinklearnt.present.HomePresentImp;
import com.example.pei.ithinklearnt.utils.DialogUtil;
import com.example.pei.ithinklearnt.utils.ToastUtil;
import com.example.pei.ithinklearnt.view.activity.DynamicDetails;
import com.example.pei.ithinklearnt.view.activity.FindNearbyPeopleActivity;
import com.example.pei.ithinklearnt.view.activity.FrescoLoaderPicturesActivity;
import com.example.pei.ithinklearnt.view.activity.UserInfoActivity0;
import com.example.pei.ithinklearnt.view.customview.dynamicSelectedDialog;
import com.example.pei.ithinklearnt.view.interfaces.HomeInterface;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;


import static android.app.Activity.RESULT_OK;
import static com.example.pei.ithinklearnt.utils.BeanOperationUtil.putBean;
import static com.example.pei.ithinklearnt.utils.DialogUtil.CreateVerifyDialog;
import static com.example.pei.ithinklearnt.utils.SnackbarUtil.ShowSnackbar;

/**
 * Created by Pei on 2017/12/6.
 */

public class HomeFragment extends Fragment implements View.OnClickListener,HomeInterface {

    private View view;
    private HomePresent homePresent;

    private RecyclerView mRecyclerView;
    private RefreshLayout mRefreshLayout;
    private NineGridTestAdapter mAdapter;
    private dynamicSelectedDialog mDynamicSelectedDialog;
    private FloatingActionButton floatingActionButton;

    private KProgressHUD hud; //等待进度条

    public final static int ADDDYNAMIC=1008;
    public final static int DYNAMICDETAILS=1009;

    private int dynamicDetailsPosition;  //用来说明点开的是哪一个position

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.homemenu_fragment, container, false);
        homePresent=new HomePresentImp(this);
        initUI();
        homePresent.initDate();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if(mAdapter!=null){
            mAdapter.notifyDataSetChanged();
        }
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        } else {
            switch (requestCode){
                case ADDDYNAMIC:
                    ShowSnackbar(getView()," 发表成功~","#FFAF70","#ffffff",16);
                    //homePresent.refresh();
                    break;
                case DYNAMICDETAILS:
                    if(data!=null){
                        mAdapter.getmList().remove(dynamicDetailsPosition);
                        mAdapter.notifyItemRemoved(dynamicDetailsPosition);

                        String key=data.getStringExtra("key");
                        if(key.equals("delete")){
                            //删除了动态
                            ShowSnackbar(getView()," 删除成功~","#FFAF70","#ffffff",16);
                        }else if(key.equals("shield")){
                            //屏蔽了那条动态
                           // ShowSnackbar(getView()," 屏蔽成功~","#FFAF70","#ffffff",16);
                        }

                    }else {
                        //返回后将点进去的那个页面重新刷新一下下下
                        homePresent.refreshOnlyOne(dynamicDetailsPosition);
                    }
                    break;
            }
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.floatbutton:
                Intent intent=new Intent("add_dynamic_Activity");
                startActivityForResult(intent,ADDDYNAMIC);
                break;
        }
    }

    @Override
    public Activity getActivityy() {
        return getActivity();
    }

    @Override
    public void finishRefresh(boolean state) {
        mRefreshLayout.finishRefresh(state);
    }

    @Override
    public void finishLoadMore(boolean state) {
        mRefreshLayout.finishLoadmore(state);
    }

    @Override
    public void adapterNotifyDataSetChanged() {
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void adapterNotifyDataOneChange(int position) {
        mAdapter.notifyItemChanged(position);
    }

    @Override
    public NineGridTestAdapter getAdapter() {
        return mAdapter;
    }

    private void initUI(){

        mRefreshLayout = view.findViewById(R.id.refreshLayout);

        floatingActionButton=view.findViewById(R.id.floatbutton);
        floatingActionButton.setOnClickListener(this);

        view.findViewById(R.id.tv_nearby).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getContext(), FindNearbyPeopleActivity.class);
                startActivity(intent);
            }
        });

        RecyclerView mRecyclerView = view.findViewById(R.id.swipe_target);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(mLayoutManager);

        mRecyclerView.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题（不过好像没什么用
        mAdapter = new NineGridTestAdapter(getContext(),new NineGridTestAdapter.itemListener(){
            @Override
            public void onThreePointClick(View v,final int position) {
                createDialog(position);
            }

            @Override
            public void onHeartClick(View v, int position) {
                homePresent.praiseAlumniCircle(position);
            }

            @Override
            public void onHeadClick(View v, int position) {
                hud = KProgressHUD.create(getActivity())
                        .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                        .setDimAmount(0.4f)
                        .setLabel("正在加载...")
                        .setCornerRadius(10)
                        .show();
                UserModel.getInstance().queryUserInfo(mAdapter.getmList().get(position).getSender().getObjectId(), new QueryUserListener() {
                    @Override
                    public void done(UserInfo s, BmobException e) {
                        hud.dismiss();
                        if(e==null){
                            Bundle bundle=new Bundle();
                            bundle.putSerializable("u",s);

                            Intent intent = new Intent();
                            intent.setClass(getActivity(), UserInfoActivity0.class);
                            intent.putExtra(getActivity().getPackageName(), bundle);
                            getActivity().startActivity(intent);
                        }else{
                            ToastUtil.ToastShow(getContext(),"请检查网络",0);
                        }
                    }
                });
            }

            @Override
            public void onItemClick(View view, int position) {
                //启动详情页活动
                Intent intent=new Intent(getContext(),DynamicDetails.class);
                AlumniCircle alumniCircle=mAdapter.getmList().get(position);
                //将动态存到本地，方便等会详情页获取数据
                putBean(getContext(),"alu","1",alumniCircle);

                intent.putExtra("permission",getPermission(position));            //能操作的权限
                intent.putExtra("isPraised",alumniCircle.getIsPraise());

                dynamicDetailsPosition=position;

                startActivityForResult(intent,DYNAMICDETAILS);
            }

            @Override
            public void onItemLongClick(View view, int position) {
                createDialog(position);
            }
        });

        mRecyclerView.setAdapter(mAdapter);

        //为swipeToLoadLayout设置下拉刷新监听者
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                homePresent.refresh();
            }
        });
        //为swipeToLoadLayout设置上拉加载更多监听者
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                homePresent.loadmore();
            }
        });

    }

    //返回为所选的item创建dialog时的权限
    private int getPermission(int position){
        int permission=0;
        if(AppApplication.getCurrentUser()!=null){
            String username=AppApplication.getCurrentUser().getUsername();
            String senderName=mAdapter.getmList().get(position).getSender().getUsername();  //发送者姓名
            int userType=AppApplication.getCurrentUser().getUserType();
            //如果是自己发送的或者是管理员 则可以删除
            if(senderName.equals(username)&&userType==1){
                //是自己发送的，且不是管理员,普通用户
                permission=1;
            } else if(senderName.equals(username)&&userType==0){
                //是自己发送的，且是管理员
                permission=2;
            }else if(!senderName.equals(username)&&userType==0){
                //不是自己发送的，但是是管理员
                permission=3;
            }else if(!senderName.equals(username)&&userType==1){
                //不是自己发送的，且不是管理员
                permission=0;
            }
        }
        return permission;
    }



    private void createDialog(final int position){
        View vieww = getLayoutInflater().inflate(R.layout.dynamic_selected_dialog, null);
        int permission=getPermission(position);
        mDynamicSelectedDialog=new dynamicSelectedDialog(getContext(), R.style.transparentFrameWindowStyle,permission, new dynamicSelectedDialog.Listener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()){
                    case R.id.btn_copy:
                        //获取剪贴板管理器：
                        ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                        // 创建普通字符型ClipData
                        ClipData mClipData = ClipData.newPlainText("Label", mAdapter.getmList().get(position).getContent());
                        // 将ClipData内容放到系统剪贴板里。
                        assert cm != null;
                        cm.setPrimaryClip(mClipData);
                        Toast.makeText(getActivity(),"已经复制好啦!",Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.btn_shield:
                        // 屏蔽某条动态
                        homePresent.shieldAlumniCircle(position);
                        break;
                    case R.id.btn_del:
                        //删除数据库里的内容
                        final SweetAlertDialog dialog=new SweetAlertDialog(getContext(), SweetAlertDialog.WARNING_TYPE);
                        dialog.setTitleText("确认删除这条主题吗?")
                              // .setContentText("确认删除这条主题吗?")
                                .setConfirmText("确定!")

                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(final SweetAlertDialog sDialog) {
                                        // reuse previous dialog instance
                                        dialog.hide();
                                        homePresent.deleteAlumniCircle(position, new HomePresent.deleteAlumniCircleListener() {
                                            @Override
                                            public void succeed() {
                                                mAdapter.getmList().remove(position);
                                                mAdapter.notifyItemRemoved(position);
                                                mAdapter.notifyItemRangeChanged(position,mAdapter.getmList().size()-position);
                                                dialog.show();
                                                sDialog.setTitleText("删除成功")
                                                        .setConfirmText("OK")
                                                        .setConfirmClickListener(null)
                                                        .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                                            }
                                            @Override
                                            public void failed() {
                                                dialog.show();
                                                sDialog.setTitleText("删除失败了")
                                                        .setConfirmText("OK")
                                                        .setContentText("网络可能出了点小状况...")
                                                        .setConfirmClickListener(null)
                                                        .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                                            }
                                        });
                                    }
                                })
                                .show();
                        dialog.setCanceledOnTouchOutside(true);


                        break;
                }
                mDynamicSelectedDialog.dismiss();
            }
        });
        mDynamicSelectedDialog.setContentView(vieww, new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT));
        Window window = mDynamicSelectedDialog.getWindow();
        // 设置显示动画
        //   window.setWindowAnimations(R.style.main_menu_animstyle);
        assert window != null;
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        // wl.y = (getWindowManager().getDefaultDisplay().getHeight());
        wl.gravity = Gravity.CENTER;
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        mDynamicSelectedDialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        mDynamicSelectedDialog.setCanceledOnTouchOutside(true);
        mDynamicSelectedDialog.show();
    }

}
